package com.devgroupvn.dota;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

public class NewsArchive
{

	public String url = "http://www.joindota.com/en/start";

	public NewsArchive()
	{
	}

	public ArrayList<Post> getListNew()
	{
		Response res = null;
		try
		{
			res = Jsoup
					.connect(url)
					.header("User-Agent",
							"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2")
					.userAgent("Mozilla").execute();
//			res =(Response) Jsoup.connect(url).get();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		Document doc = null;
		try
		{
			doc = res.parse();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		ArrayList<Post> listpost = new ArrayList<Post>();

		Element item = doc.select(".pad").first();

		Post temp = new Post();

		item = doc.select(".light").first();
		Elements listitems = item.select(".news_thumb");
		for (Element link : listitems)
		{
			temp = new Post();

			temp.link = link.select("a").first().attr("href");
			temp.img = link.select("img").first().attr("src");
			temp.title = link.nextElementSibling().text();//attr("href");
			temp.description =  ((TextNode) link.nextElementSibling().nextSibling()).text();
			listpost.add(temp);

		}
		return listpost;
	}

	public Post getPost(String url)
	{
		try
		{

			Response res = Jsoup
					.connect(url)
					.header("User-Agent",
							"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2")
					.userAgent("Mozilla").execute();

			Document doc = res.parse();

			Element item = doc.select(".pad").first();
			Element h1 = item.select("h1").first();

			Element div = h1.nextElementSibling();

			div.remove();
			h1.remove();

			Post post = new Post();
			post.content = item.html();
			return post;
		}
		catch (Exception e)
		{
			System.out.println(e.toString());
		}
		return null;
	}
}
